package zouran.login.emailUtil;

import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author zouran
 * createDate：2023/5/13  10:37
 */
@Component
public class SendEmail {
    //验证码有效期
    private static final Integer validity=5;
    public static final String TITLE_LOGON="账号注册";//邮箱标题
    public static final String TITLE_LOGON_SUCCESS="账号注册成功";//邮箱标题
    /**
     *发送邮箱
     * @param target 收件人邮箱
     * @param content 邮箱内容
     * @param title 邮箱标题
     */
    public boolean send(String target,String content,String title) {
        final Properties properties=new Properties();
        properties.put("mail.user",MyEmailConfig.USER);
        properties.put("mail.password",MyEmailConfig.PASSWORD);
        properties.put("mail.smtp.auth","true");
        properties.put("mail.smtp.host",MyEmailConfig.getHost());
        Authenticator authenticator=new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String user=properties.getProperty("mail.user");
                String password=properties.getProperty("mail.password");
                return new PasswordAuthentication(user, password);
            }
        };
        Session mailSession= Session.getInstance(properties, authenticator);
        MimeMessage message=new MimeMessage(mailSession);
        String userName=properties.getProperty("mail.user");
        try {
            //发送人邮箱
            InternetAddress fromAddress = new InternetAddress(userName);
            message.setFrom(fromAddress);
            //收件人
            InternetAddress targetAddress = new InternetAddress(target);
            message.setRecipients(MimeMessage.RecipientType.TO, new InternetAddress[]{targetAddress});
            //邮箱内容
            message.setContent(content, "text/html;charset=UTF-8");
            //邮箱标题
            message.setSubject(title);
            //邮箱发送
            Transport.send(message);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    public String logonContent(String captcha){
        return "亲爱的用户:\n"+"您正在进行注册,验证码为:"+captcha+"\n"+"请在"+validity+"分钟内完成验证。";
    }
    public String loginSuccessContent(){
        return "亲爱的用户:\n"+"恭喜您注册成功,感谢您的使用";
    }
}
